﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;

namespace Reconciliation.Data
{
    public partial class OrderDetail
    {
        public static Domain.OrderDetail MapDataToDomain(Data.OrderDetail dataOrderDetail)
        {
            Domain.OrderDetail domainOrderDetail = new Reconciliation.Domain.OrderDetail();
            if(dataOrderDetail.Cassette_1 != null)
                domainOrderDetail.Cassette = Cassette.MapDataToDomain(dataOrderDetail.Cassette_1) ;            
            domainOrderDetail.Consensio = dataOrderDetail.Consensio.Value ;
            domainOrderDetail.CPC = dataOrderDetail.CPC.Value ;
            if (dataOrderDetail.Denomination != null)
                domainOrderDetail.Denomination = Denomination.MapDataToDomain(dataOrderDetail.Denomination) ;
            domainOrderDetail.ExpectedReturn  = dataOrderDetail.ExpectedReturn.Value ;
            domainOrderDetail.OrderDetailID = dataOrderDetail.OrderDetailID ;
            domainOrderDetail.OrderValue = dataOrderDetail.OrderValue.Value ;
            domainOrderDetail.PhysicalReturn = dataOrderDetail.PhysicalReturn.Value ;
            domainOrderDetail.SST= dataOrderDetail.SST.Value ;
            return domainOrderDetail;
        }

        public static void SetPackagingOrderDetail(Domain.OrderDetail domainOrderDetail)
        {
            try
            {
                using (ReconciliationEntities recEnt = new ReconciliationEntities())
                {
                    Data.OrderDetail dataOrderDetail = recEnt.OrderDetail.Where(od => od.OrderDetailID.Equals(domainOrderDetail.OrderDetailID)).FirstOrDefault();
                    if (dataOrderDetail == null)
                    {
                        dataOrderDetail.CPC = domainOrderDetail.OrderValue;
                        recEnt.SaveChanges();
                    }
                    else
                    {
                        throw new Exception("No order detail exists.");
                    }
                }
            }
            catch (EntityException ex)
            {
                ExceptionPolicy.HandleException(ex, "Exception Policy");
                throw new Domain.ReconciliationException("Database exception occured please try again later.");
            }
            catch (Exception ex)
            {
                ExceptionPolicy.HandleException(ex, "Exception Policy");
                throw new Domain.ReconciliationException("Unable to update order.");
            }
        }
    }
}
